<template>
  <!-- 应用容器，提供统一的页面样式 -->
  <div class="app-container out-div-global">
    <div class="inner-div-normal">
      <!-- 查询表单，用于筛选表单配置数据 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
        <!-- 表单编码查询条件 -->
        <el-form-item label="编码" prop="formCode">
          <el-input
              v-model="queryParams.formCode"
              placeholder="请输入编码"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- 表单类型查询条件 -->
        <el-form-item label="表单类型" prop="formType">
          <el-select v-model="queryParams.formType" placeholder="请选择表单类型" clearable style="width: 120px">
            <el-option
                v-for="dict in sys_form_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- 行政区划级别查询条件 -->
        <el-form-item label="行政区划级别" prop="adminLevel">
          <el-select v-model="queryParams.adminLevel" placeholder="请选择行政区划级别" clearable style="width: 120px">
            <el-option
                v-for="dict in sys_admin_level"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- 查询和重置按钮 -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮行 -->
      <el-row :gutter="10" class="mb8">
        <!-- 新增按钮 -->
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:formconfig:add']"
          >新增
          </el-button>
        </el-col>
        <!-- 修改按钮 -->
        <el-col :span="1.5">
          <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:formconfig:edit']"
          >修改
          </el-button>
        </el-col>
        <!-- 删除按钮 -->
        <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:formconfig:remove']"
          >删除
          </el-button>
        </el-col>
        <!-- 导出按钮 -->
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:formconfig:export']"
          >导出
          </el-button>
        </el-col>
        <!-- 右侧工具栏 -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>
    <div class="inner-div-auto">
      <!-- 表单配置数据表格 -->
      <el-table v-loading="loading" :data="formconfigList" @selection-change="handleSelectionChange">
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" align="center"/>
        <!-- 编码列 -->
        <el-table-column label="编码" align="center" prop="formCode"/>
        <!-- 表单名称列 -->
        <el-table-column label="表单名称" align="center" prop="formName"/>
        <!-- 表单类型列 -->
        <el-table-column label="表单类型" align="center" prop="formType">
          <template #default="scope">

            <dict-tag :options="sys_form_type" :value="scope.row.formType"/>
          </template>
        </el-table-column>
        <!-- 行政区划级别列 -->
        <el-table-column label="行政区划级别" align="center" prop="adminLevel">
          <template #default="scope">
            <dict-tag :options="sys_admin_level" :value="scope.row.adminLevel"/>
          </template>
        </el-table-column>
        <!-- 状态列 -->
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:formconfig:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['system:formconfig:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改表单配置对话框 -->
    <el-dialog :title="title" v-model="open" width="90%" append-to-body style="height: 85vh">
      <el-form ref="formconfigRef" :model="form" :rules="rules" label-width="140px">
        <!-- 第一行表单字段 -->
        <el-row :gutter="4">
          <!-- 编码输入框 -->
          <el-col :span="4">
            <el-form-item label="编码" prop="formCode">
              <el-input v-model="form.formCode" placeholder="请输入编码"/>
            </el-form-item>
          </el-col>
          <!-- 表单名称输入框 -->
          <el-col :span="4">
            <el-form-item label="表单名称" prop="formName">
              <el-input v-model="form.formName" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <!-- 表单类型选择框 -->
          <el-col :span="4">
            <el-form-item label="表单类型" prop="formType">
              <el-select v-model="form.formType" placeholder="请选择表单类型">
                <el-option
                    v-for="dict in sys_form_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 行政区划级别选择框 -->
          <el-col :span="4">
            <el-form-item label="行政区划级别" prop="adminId">
              <el-select v-model="form.adminLevel" placeholder="请选择行政区划级别">
                <el-option
                    v-for="dict in sys_admin_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="年份" prop="adminId" style="width: 100%">
              <el-date-picker
                  v-model="form.year"
                  format="YYYY"
                  type="year"
                  placeholder="请选择年份 "
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请选择行政区" prop="adminCodeOne">
              <el-row :gutter="24">
                <el-col :span="6" >
                  <el-select
                      v-model="form.adminCodeOne"
                      placeholder="请选择一级行政区"
                      @change="handleAdminLevelOneChange" style="width: 250px">
                    <el-option
                        v-for="dict in administrativeOptions"
                        :key="dict.administrativeCode"
                        :label="dict.administrativeName"
                        :value="dict.administrativeCode">
                    </el-option>
                  </el-select>
                </el-col>

                <el-col :span="6">
                  <el-select
                      v-model="form.adminCodeTwo"
                      placeholder="请选择二级行政区"
                      @change="handleAdminLevelTwoChange"
                      :disabled="!form.adminCodeOne"  style="width: 250px">
                    <el-option
                        v-for="dict in administrativeOptionsLevelTwo"
                        :key="dict.administrativeCode"
                        :label="dict.administrativeName"
                        :value="dict.administrativeCode">
                    </el-option>
                  </el-select>
                </el-col>

                <el-col :span="6">
                  <el-select
                      v-model="form.adminCodeThree"
                      placeholder="请选择三级行政区"
                      @change="handleAdminLevelThreeChange"
                      :disabled="!form.adminCodeTwo"  style="width: 350px">
                    <el-option
                        v-for="dict in administrativeOptionsLevelThree"
                        :key="dict.administrativeCode"
                        :label="dict.administrativeName"
                        :value="dict.administrativeCode">
                    </el-option>
                  </el-select>
                </el-col>

                <el-col :span="6">
                  <el-tree-select
                      v-model="form.adminCodeOther"
                      :data="administrativeOptionsLevelOther"
                      :props="{ value: 'administrativeCode', label: 'administrativeName', children: 'children' }"
                      value-key="administrativeId"
                      placeholder="请选择父级"
                      check-strictly
                  />
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>


        </el-row>
        <!-- 表单设计器区域 -->
        <el-row>
          <el-col :span="24" style="height: 600px">
            <EDesigner
                ref="designerRef"
                title="表单设计器"
                hiddenHeader="true"
                class="designer-container"
            >
              <template #header-prefix>
                <div>欢迎使用表单设计器</div>
              </template>
            </EDesigner>
          </el-col>
        </el-row>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="preview">预 览</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Formconfig" lang="ts">
// 导入表单配置相关的API接口
import {listFormconfig, getFormconfig, delFormconfig, addFormconfig, updateFormconfig} from "@/api/system/formconfig"
// 导入行政区划相关的API接口
import {listAdministrative, listAdministrativeByTree} from "@/api/system/administrative";
// 导入表单设计器组件及相关类型
import {EDesigner, PageSchema} from "epic-designer";
// 获取当前Vue组件实例
const {proxy} = getCurrentInstance()
// 导入Vue相关函数
import {ref, reactive, toRefs, getCurrentInstance, watch} from 'vue';

// 加载系统状态字典(正常/停用)
const {sys_normal_disable} = proxy.useDict("sys_normal_disable")
// 加载表单类型字典
const {sys_form_type} = proxy.useDict('sys_form_type')
const {sys_admin_level} = proxy.useDict('sys_admin_level')
// 获取表单设计器组件引用
const designerRef = ref<InstanceType<typeof EDesigner>>();

// 各级行政区划选项数据
const administrativeOptions = ref([])
const administrativeOptionsLevelTwo = ref([])
const administrativeOptionsLevelThree = ref([])
const administrativeOptionsLevelOther = ref([])
// 存储表单配置列表数据
const formconfigList = ref([])
// 控制对话框显示状态
const open = ref(false)
// 控制表格加载状态
const loading = ref(true)
// 控制搜索栏显示状态
const showSearch = ref(true)
// 存储选中的数据项ID数组
const ids = ref([])
// 控制单选按钮禁用状态
const single = ref(true)
// 控制多选按钮禁用状态
const multiple = ref(true)
// 存储数据总条数
const total = ref(0)
// 存储对话框标题
const title = ref("")

// 响应式数据对象，包含表单数据和查询参数
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    formCode: null,
    formJson: null,
    formName: null,
    formType: null,
    adminId: null,
    status: null,
    adminLevel: null
  },
  rules: {
    formCode: [
      {required: true, message: "编码不能为空", trigger: "blur"}
    ],
    formName: [
      {required: true, message: "编码不能为空", trigger: "blur"}
    ],
    formType: [
      {required: true, message: "表单类型不能为空", trigger: "change"}
    ], adminCodeOne: [
      {required: true, message: "行政区划不能为空", trigger: "change"}
    ],
    adminCodeTwo: [
      {required: true, message: "行政区划不能为空", trigger: "change"}
    ],
    adminCodeThree: [
      {required: true, message: "行政区划不能为空", trigger: "change"}
    ],
    adminCodeOther: [
      {required: true, message: "行政区划不能为空", trigger: "change"}
    ],
    adminLevel: [
      {required: true, message: "行政区划级别不能为空", trigger: "change"}
    ],

    status: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
  }
})

// 解构响应式数据，使模板可以直接访问
const {queryParams, form, rules} = toRefs(data)


/** 查询表单配置列表 */
function getList() {
  // 设置加载状态
  loading.value = true
  // 调用API获取表单配置列表
  listFormconfig(queryParams.value).then(response => {
    // 设置表格数据
    formconfigList.value = response.rows
    // 设置总条数
    total.value = response.total
    // 取消加载状态
    loading.value = false
  })
}

// 取消按钮处理函数
function cancel() {
  // 关闭对话框
  open.value = false
  // 重置表单
  reset()
}

// 表单重置处理函数
function reset() {
  // 重置表单数据
  form.value = {
    id: null,
    formCode: null,
    formJson: null,
    formType: null,
    formName: null,
    adminId: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  // 重置表单设计器
  designerRef.value?.reset()
  // 重置表单验证状态
  proxy.resetForm("formconfigRef")
}


/** 搜索按钮操作 */
function handleQuery() {
  // 重置页码为第一页
  queryParams.value.pageNum = 1
  // 执行查询
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  // 重置查询表单
  proxy.resetForm("queryRef")
  // 执行查询
  handleQuery()
}

// 多选框选中数据处理函数
function handleSelectionChange(selection) {
  // 获取选中项的ID数组
  ids.value = selection.map(item => item.id)
  // 控制单选按钮状态(只有选中一项时才可用)
  single.value = selection.length != 1
  // 控制多选按钮状态(有选中项时才可用)
  multiple.value = !selection.length
}

/** 预览操作 */
function preview() {
  // 调用表单设计器的预览功能
  designerRef.value?.preview()
}

/** 新增按钮操作 */
async function handleAdd() {
  // 异步重置表单
  await reset()
  // 打开对话框
  open.value = true
  // 设置对话框标题
  title.value = "添加表单配置";

  getlistAdministrative('0');

}

/** 修改按钮操作 */
async function handleUpdate(row) {
  // 打开对话框
  open.value = true
  // 设置加载状态
  loading.value = true
  // 重置表单
  reset()
  // 获取要修改的数据ID
  const _id = row.id || ids.value
  getlistAdministrative('0');
  // 获取表单配置详情
  getFormconfig(_id).then(response => {
    // 设置表单数据
    form.value = response.data;
    form.value.year = JSON.stringify(form.value.year);
    // 设置表单设计器数据
    designerRef.value?.setData(JSON.parse(form.value.formJson))
    // 设置对话框标题
    title.value = "修改表单配置"
    // 行政区划级联回显
    loadAdministrativeForEdit(form.value)
  }).finally(() => {
    // 取消加载状态
    loading.value = false
  })
}

function getlistAdministrative(parentCode) {
  listAdministrative({parentCode: parentCode}).then(response => {
    administrativeOptions.value = []
    administrativeOptions.value = response.data
  })
};

/** 提交按钮 */
function submitForm() {
  // 获取表单设计器数据
  const json = designerRef.value?.getData();
  console.log(json);
  // 将数据转换为JSON字符串
  form.value.formJson = JSON.stringify(json);
  if (form.value.year instanceof Date) {
    form.value.year = form.value.year.getFullYear().toString();
  }
  // 表单验证
  proxy.$refs["formconfigRef"].validate(valid => {
    if (valid) {
      // 根据是否有ID判断是更新还是新增
      if (form.value.id != null) {
        // 更新表单配置
        updateFormconfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 新增表单配置
        addFormconfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 获取要删除的数据ID
  const _ids = row.id || ids.value
  // 确认删除操作
  proxy.$modal.confirm('是否确认删除表单配置编号为"' + _ids + '"的数据项？').then(function () {
    // 调用删除API
    return delFormconfig(_ids)
  }).then(() => {
    // 刷新列表
    getList()
    // 显示删除成功消息
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  // 下载导出文件
  proxy.download('system/formconfig/export', {
    ...queryParams.value
  }, `formconfig_${new Date().getTime()}.xlsx`)
}

// 一级行政区变更事件
function handleAdminLevelOneChange(value) {
  // 清空后续级别的选择
  form.value.adminCodeTwo = ''
  form.value.adminCodeThree = ''
  form.value.adminCodeOther = ''

  // 根据一级行政区获取二级行政区数据
  if (value) {
    listAdministrative({parentCode: value}).then(response => {
      console.info("🚀 ~ file:index method: line:573 -----", response)
      administrativeOptionsLevelTwo.value = []
      administrativeOptionsLevelTwo.value = response.data
    })
  } else {
    administrativeOptionsLevelTwo.value = []
  }

  // 清空三级及以下数据
  administrativeOptionsLevelThree.value = []
  administrativeOptionsLevelOther.value = []
}

// 二级行政区变更事件
function handleAdminLevelTwoChange(value) {
  // 清空后续级别的选择
  form.value.adminCodeThree = ''
  form.value.adminCodeOther = ''
  // 根据二级行政区获取三级行政区数据
  if (value) {
    listAdministrative({parentCode: value}).then(response => {
      administrativeOptionsLevelThree.value = []
      administrativeOptionsLevelThree.value = response.data
    })
  } else {
    administrativeOptionsLevelThree.value = []
  }
  // 清空详细级数据
  administrativeOptionsLevelOther.value = []
}

// 三级行政区变更事件
function handleAdminLevelThreeChange(value) {
  // 清空详细级别的选择
  form.value.adminCodeOther = ''

  // 根据三级行政区获取详细行政区数据
  if (value) {
    listAdministrativeByTree({parentCode: value}).then(response => {
      // 清空选项数组
      administrativeOptionsLevelOther.value = []
      // 创建顶级节点数据
      administrativeOptionsLevelOther.value=response.data
    })
  } else {
    administrativeOptionsLevelOther.value = []
  }
}

// 编辑时加载行政区划数据
function loadAdministrativeForEdit(formData) {
  // 加载一级行政区划
  getlistAdministrative('0');

  // 如果有一级行政区划代码，加载二级行政区划
  if (formData.adminCodeOne) {
    listAdministrative({parentCode: formData.adminCodeOne}).then(response => {
      administrativeOptionsLevelTwo.value = response.data

      // 如果有二级行政区划代码，加载三级行政区划
      if (formData.adminCodeTwo) {
        listAdministrative({parentCode: formData.adminCodeTwo}).then(response => {
          administrativeOptionsLevelThree.value = response.data

          // 如果有三级行政区划代码，加载详细行政区划
          if (formData.adminCodeThree) {
            listAdministrativeByTree({parentCode: formData.adminCodeThree}).then(response => {
              administrativeOptionsLevelOther.value = response.data
            })
          }
        })
      }
    })
  }
}
// 监听行政区划数据变化，初始化一级数据
watch(administrativeOptions, (newVal) => {
  if (newVal && newVal.length > 0) {
    // 初始化一级数据
    administrativeOptionsLevelTwo.value = []
    administrativeOptionsLevelThree.value = []
    administrativeOptionsLevelOther.value = []
  }
})
// 初始化加载数据
getList()
</script>
<!--<style scoped>-->
<!--.designer-container{-->
<!--  .el-form-item__label{-->
<!--    font-weight: normal;-->
<!--    font-size: 12px;-->
<!--    text-align: right;-->
<!--    width: 50%;-->
<!--    display: contents;-->
<!--  }-->
<!--}-->
<!--</style>-->
